#!/bin/bash
#
# Generates a new public/private keypair
#
# Author:   Dr. Mike Murphy (mmurphy2@coastal.edu)
# Revision: 19 November 2013
#
#   Copyright 2012-2013 Coastal Carolina University
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#


## p_cmd_generate_key_help
##
## Echoes help information for the generate_key command. Returns 0.
##
function p_cmd_generate_key_help() {
	cat << EOF
Usage: pulley generate_key [options] [-- <expert options>]

Generates a new public/private keypair for signing subscriptions or other
uses in Pulley.

Available Options

--section <section>
  Generate the new key inside the given <section> of the Pulley key store.
  By default, the subscription section is used.

--security <provider>
  Use the specified security <provider>. By default, the security provider
  configured for use with the subscription is used.

Expert options can be passed to the security provider's key generation
routines by passing them after a -- to indicate the end of command options.
EOF
	return 0
}


## p_cmd_generate_key_summary
##
## Echoes summary information for the generate_key command. Returns 0.
##
function p_cmd_generate_key_summary() {
	echo "Generates a new security public/provide keypair"
	return 0
}


## p_cmd_generate_key [expert gpg options]
##
## Implements the generate_key command, which generates a new GPG key for
## signing payloads. Returns 0 on success, non-zero on failure.
##
function p_cmd_generate_key() {
	local section="subscription"
	local provider=$(psub_get_provider)
	
	local lopts="security:,section:"
	local args=$(getopt -o "+" -l "${lopts}" -n "$0" -- "$@")
	local status=$?
	
	if ((status == 0)); then
		eval set -- "${args}"
		
		while [[ "$1" != "--" ]]; do
			case "$1" in
				--security)
					shift
					provider="$1"
					shift
				;;
				--section)
					shift
					section="$1"
					shift
				;;
			esac
		done
		
		shift
		
		psec_generate_key "${section}" "${provider}" "$@"
		status=$?
	fi
	
	return ${status}
}
